<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>授权系统</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11.3.0/dist/sweetalert2.min.css">
    <link rel="stylesheet" href="assets/css/index.css">
    <style>
   body {
    font-family: system-ui, -apple-system, sans-serif;
    background: url('./bg.png') no-repeat center center fixed; /* 替换为你的背景图片地址 */
    background-size: cover;
    backdrop-filter: blur(10px); /* 添加模糊效果，值越大越模糊 */
    margin: 0;
    padding: 0;
    color: #495057;
}
/* 背景模糊层 */
.background-blur {
    position: fixed; /* 固定位置 */
    top: 0;
    left: 0;
    width: 100%; /* 宽度覆盖整个屏幕 */
    height: 100%; /* 高度覆盖整个屏幕 */
    background: url('https://example.com/your-background-image.jpg') no-repeat center center fixed; /* 替换为你的背景图片地址 */
    background-size: cover; /* 确保图片覆盖整个背景 */
    filter: blur(10px); /* 高斯模糊效果，值越大越模糊 */
    z-index: -1; /* 确保背景层在内容层下方 */
}

    .containers {
        text-align: center;
        padding: 10px;
        background: rgba(255, 255, 255, 0.4);
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
        border-radius: 18px;
        margin: 18px;
        max-width: 500px;
        
    }

    h1 {
        font-size: 24px;
        font-weight: 600;
        color: #2c7be5;
        margin-bottom: 20px;
    }

    .button-container {
        display: flex;
        justify-content: center;
        gap: 16px;
        margin-top: 20px;
    }

    .neumorphism-button {
        background: #fff;
        border: none;
        padding: 12px 24px;
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
        cursor: pointer;
        font-size: 12px;
        color: #495057;
        transition: all 0.3s ease;
    }

    .neumorphism-button:hover {
        background: #f8f9fa;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }

    .container {
        max-width: 500px;
        margin: 10px;
        padding: 10px;
         background: rgba(255, 255, 255, 0.4);
        border-radius: 28px;
        box-shadow: 0 2px 199px rgba(0, 0, 0, 0.05);
    }

    .page {
        display: none;
        padding: 20px;
    }

    .page.active {
        display: block;
    }

    form {
        display: flex;
        flex-direction: column;
        gap: 16px;
    }

    label {
        font-size: 14px;
        font-weight: 500;
        color: #495057;
    }

    input, select {
        padding: 10px;
        border: 1px solid #e9ecef;
        border-radius: 6px;
        font-size: 14px;
        transition: border-color 0.3s, box-shadow 0.3s;
    }

    input:focus, select:focus {
        border-color: #2c7be5;
        box-shadow: 0 0 0 3px rgba(44, 123, 229, 0.1);
        outline: none;
    }

    button[type="submit"] {
        background: #2c7be5;
        color: #fff;
        border: none;
        padding: 10px;
        border-radius: 6px;
        font-size: 14px;
        cursor: pointer;
        transition: background 0.3s;
    }

    button[type="submit"]:hover {
        background: #2868c7;
    }
button[type="pay"] {
        background: #2c7be5;
        color: #fff;
        border: none;
        padding: 10px;
        border-radius: 6px;
        font-size: 10px;
        cursor: pointer;
        transition: background 0.3s;
    }

    button[type="pay"]:hover {
        background: #2868c7;
    }
    #payment-options {
        display: flex;
        gap: 10px;
        margin-top: 20px;
    }

    #payment-options button {
        background: #fff;
        border: 1px solid #e9ecef;
        padding: 10px 20px;
        border-radius: 6px;
        cursor: pointer;
        font-size: 14px;
        color: #495057;
        transition: all 0.3s ease;
    }

    #payment-options button:hover {
        background: #f8f9fa;
        border-color: #2c7be5;
        color: #2c7be5;
    }
    </style>
</head>
<body>
    <br>
    <div class="containers">
        <h1>授权系统</h1>
        <div class="button-container">
            <button class="neumorphism-button" onclick="showPage('online-authorization')">在线授权</button>
            <button class="neumorphism-button" onclick="showPage('auth')">卡密授权</button>
            <button class="neumorphism-button" onclick="showPage('query')">查询功能</button>
        </div>
    </div>
    <br>
    <br>
        <br>
            <br>    <br>    <br>

    <div class="container">
        <!-- 在线授权 -->
        <div class="background-blur"></div>

        <div id="online-authorization" class="page">
            <form id="onlineAuthForm">
                <label for="lxr">联系人QQ:</label>
                <input type="text" id="lxr" name="lxr" placeholder="请输入联系人QQ...." required>
                <label for="jqr">机器人QQ:</label>
                <input type="text" id="jqr" name="jqr" placeholder="请输入机器人QQ...." required>
                <label for="duration">授权时长:</label>
                <select id="duration" name="duration" class="custom-select">
                    <option value="月">月(NEW)</option>
                    <option value="年">年(NEW)</option>
                    <option value="永久">永久(NEW)</option>
                </select>
                <button class="neumorphism-button" type="submit">授权</button>
            </form>
            <div id="payment-options" style="display: none;">
                <button type="pay" onclick="selectPayment('qqpay', calculatePrice())">QQ</button>
                <button type="pay" onclick="selectPayment('wxpay', calculatePrice())">微信</button>
                <button type="pay" onclick="selectPayment('alipay', calculatePrice())">支付宝</button>
            </div>
        </div>

        <!-- 查询功能 -->
        <div id="query" class="page">
            <form id="queryAuthForm">
                <h2>查询授权</h2>
                <label for="queryAuthQQ">请输入QQ号：</label>
                <input type="text" id="queryAuthQQ" name="queryAuthQQ" required>
                <button type="submit">查询</button>
            </form>
            <form id="queryKamiForm" style="margin-top: 20px;">
                <h2>查询卡密</h2>
                <label for="queryKamiInput">请输入卡密：</label>
                <input type="text" id="queryKamiInput" name="queryKamiInput" required>
                <button type="submit">查询</button>
            </form>
        </div>

        <!-- 卡密授权 -->
        <div id="auth" class="page">
            <form id="authForm">
                <label for="lxqq">联系人QQ:</label>
                <input type="text" id="lxqq" name="lxqq" placeholder="请输入联系人QQ号...." required>
                <label for="sqqq">机器人QQ:</label>
                <input type="text" id="sqqq" name="sqqq" placeholder="请输入机器人QQ号...." required>
                <label for="kami1">卡密:</label>
                <input type="text" id="kami1" name="kami1" placeholder="请输入卡密...." required>
                <button type="submit">授权</button>
            </form>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.3.0/dist/sweetalert2.min.js"></script>
    <script src="assets/js/main.js"></script>
    <script>
    // 页面切换逻辑
    function showPage(pageId) {
        document.querySelectorAll('.page').forEach(page => {
            page.style.display = 'none';
        });
        document.getElementById(pageId).style.display = 'block';
    }

    // 初始化显示在线授权页面
    showPage('online-authorization');

    // 页面加载时获取价格信息并更新选择框
    function updateDurationOptions() {
        fetch('api/price.php')
            .then(response => {
                if (!response.ok) {
                    throw new Error('无法获取价格信息');
                }
                return response.json();
            })
            .then(data => {
                const durationSelect = document.getElementById('duration');
                durationSelect.innerHTML = '';
                const monthlyOption = document.createElement('option');
                monthlyOption                .value = '月';
                monthlyOption.text = `月(${data.monthly_price}元)`;
                durationSelect.appendChild(monthlyOption);

                const yearlyOption = document.createElement('option');
                yearlyOption.value = '年';
                yearlyOption.text = `年(${data.yearly_price}元)`;
                durationSelect.appendChild(yearlyOption);

                const lifetimeOption = document.createElement('option');
                lifetimeOption.value = '永久';
                lifetimeOption.text = `永久(${data.lifetime_price}元)`;
                durationSelect.appendChild(lifetimeOption);
            })
            .catch(error => {
                console.error('获取价格信息失败:', error);
                Swal.fire({
                    title: '加载失败',
                    text: '无法获取授权时长的价格信息，请稍后再试！',
                    icon: 'error'
                });
            });
    }

    // 页面加载时更新选择框
    window.onload = function() {
        updateDurationOptions();
    };

    // 授权表单提交事件
    document.getElementById('onlineAuthForm').addEventListener('submit', function(event) {
        event.preventDefault(); // 阻止表单默认提交行为

        const lxr = document.getElementById('lxr').value; // 联系人QQ
        const jqr = document.getElementById('jqr').value; // 机器人QQ
        const duration = document.getElementById('duration').value; // 授权时长

        fetch('api/price.php')
            .then(response => {
                if (!response.ok) {
                    throw new Error('无法获取价格信息');
                }
                return response.json();
            })
            .then(data => {
                let price = 0;
                switch (duration) {
                    case '月':
                        price = data.monthly_price;
                        break;
                    case '年':
                        price = data.yearly_price;
                        break;
                    case '永久':
                        price = data.lifetime_price;
                        break;
                }

                const paymentOptions = document.getElementById('payment-options');
                paymentOptions.style.display = 'flex';
                paymentOptions.innerHTML = `
                    <button type="pay" onclick="selectPayment('qqpay', ${price})">QQ</button>
                    <button type="pay" onclick="selectPayment('wxpay', ${price})">微信</button>
                    <button type="pay" onclick="selectPayment('alipay', ${price})">支付宝</button>
                `;
            })
            .catch(error => {
                console.error('获取价格信息失败:', error);
                Swal.fire({
                    title: '授权失败',
                    text: '无法获取授权时长的价格信息，请稍后再试！',
                    icon: 'error'
                });
            });
    });

    // 支付方式选择函数
    function selectPayment(paymentMethod, price) {
    const lxr = document.getElementById('lxr').value; // 联系人QQ
    const jqr = document.getElementById('jqr').value; // 机器人QQ
    const duration = document.getElementById('duration').value; // 授权时长

    if (!lxr || !jqr || !duration || !paymentMethod || price <= 0) {
        Swal.fire({
            title: '参数错误',
            text: '请确保所有字段都已正确填写！',
            icon: 'error',
        });
        return;
    }

    const orderInfo = {
        type: paymentMethod,
        out_trade_no: generateOrderNumber(), // 生成订单号（包含秒数）
        money: price,
        name: `授权服务-${duration}`,
        jqr: jqr,
        lxr: lxr
    };

    const queryParams = new URLSearchParams(orderInfo).toString();
    fetch(`api/payment.php?${queryParams}`, { method: 'GET' })
        .then(response => response.json())
        .then(data => {
            if (data.code == 200) {
                if (data.data.qrcode) {
                    const encodedQrcode = encodeURIComponent(data.data.qrcode);
                    const qrcodeUrl = `http://154.64.244.235/qrcode.php?text=${encodedQrcode}`;
                    Swal.fire({
                        title: '请不要离开本页面\n',
                        imageUrl: qrcodeUrl,
                        imageAlt: '支付二维码',
                        html: `
                            <p>支付二维码已生成，请扫码支付。</p>
                            <p>订单号：${orderInfo.out_trade_no}</p>
                            <a href="${data.data.qrcode}" target="_blank" class="neumorphism-button">点击这里查看链接</a>
                        `,
                        timer: 180000, // 3分钟倒计时
                        timerProgressBar: true,
                        didOpen: () => {
                            Swal.showLoading();
                            checkOrderStatus(orderInfo.out_trade_no); // 使用完整的订单号
                        },
                        willClose: () => {
                            clearInterval(intervalId);
                        }
                    });
                } else if (data.data.code_url) {
                    Swal.fire({
                        title: '请扫码支付',
                        imageUrl: data.data.code_url,
                        imageAlt: '支付二维码',
                        timer: 180000, // 3分钟倒计时
                        timerProgressBar: true,
                        didOpen: () => {
                            Swal.showLoading();
                            checkOrderStatus(orderInfo.out_trade_no); // 使用完整的订单号
                        },
                        willClose: () => {
                            clearInterval(intervalId);
                        }
                    });
                } else {
                    window.location.href = data.data.pay_url;
                }
            } else {
                Swal.fire({
                    title: '支付失败',
                    text: data.msg,
                    icon: 'error',
                });
            }
        })
        .catch(error => {
            console.error('支付请求失败:', error);
            Swal.fire({
                title: '支付失败',
                text: '无法完成支付请求，请稍后再试！',
                icon: 'error',
            });
        });
}

    // 生成订单号（包含秒数）
    function generateOrderNumber() {
        const now = new Date();
        const year = now.getFullYear(); // 年
        const month = String(now.getMonth() + 1).padStart(2, '0'); // 月（+1是因为getMonth()返回的是0-11）
        const day = String(now.getDate()).padStart(2, '0'); // 日
        const hours = String(now.getHours()).padStart(2, '0'); // 小时
        const minutes = String(now.getMinutes()).padStart(2, '0'); // 分钟
        const seconds = String(now.getSeconds()).padStart(2, '0'); // 秒数

        return `${year}${month}${day}${hours}${minutes}${seconds}`;
    }

    // 检查订单状态
    function checkOrderStatus(orderNo) {
    let intervalId = setInterval(() => {
        fetch(`api/order_yz.php?order_no=${orderNo}`)
            .then(response => response.json())
            .then(data => {
                if (data.data.status == 1) {
                    clearInterval(intervalId);
                    Swal.fire({
                        title: '支付成功',
                        text: '感谢您的支持！',
                        icon: 'success',
                        showConfirmButton: true, // 显示确认按钮
                        confirmButtonText: '返回首页', // 按钮文本
                    }).then((result) => {
                        if (result.isConfirmed) {
                            // 用户点击按钮后刷新页面
                            window.location.reload();
                        }
                    });
                }
            })
       
    }, 1000); // 每1秒检查一次
}
    // 查询授权信息
    document.getElementById('queryAuthForm').addEventListener('submit', function(event) {
        event.preventDefault(); // 阻止表单默认提交行为

        const queryAuthQQ = document.getElementById('queryAuthQQ').value;

        // 发起请求查询授权信息
        fetch(`api/cx.php?qq=${queryAuthQQ}`)
            .then(response => {
                if (!response.ok) {
                    throw new Error('请求失败');
                }
                return response.json();
            })
            .then(data => {
                if (data.code == 200) {
                    // 格式化时间戳
                    const nowTimeFormatted = formatDate(data.now_time);
                    const vipTimeFormatted = formatDate(data.vip_time);

                    // 显示查询结果
                    Swal.fire({
                        title: '查询结果',
                        html: `
                            <p>QQ号: ${queryAuthQQ}</p>
                            <p>添加时间: ${nowTimeFormatted}</p>
                            <p>到期时间: ${vipTimeFormatted}</p>
                        `,
                        icon: 'info'
                    });
                } else {
                    // 查询失败
                    Swal.fire({
                        title: '查询失败',
                        text: data.message || '未找到授权信息！',
                        icon: 'error'
                    });
                }
            })
            .catch(error => {
                // 显示错误信息
                Swal.fire({
                    title: '查询失败',
                    text: error.message,
                    icon: 'error'
                });
            });
    });

    // 时间戳格式化函数
    function formatDate(timestamp) {
        const date = new Date(timestamp * 1000); // 将时间戳转换为毫秒
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要加
               const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');

        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    }

    // 查询卡密信息
    document.getElementById('queryKamiForm').addEventListener('submit', function(event) {
        event.preventDefault(); // 阻止表单默认提交行为

        const queryKamiInput = document.getElementById('queryKamiInput').value;

        // 发起请求查询卡密信息
        fetch(`api/kmcx.php?kami=${queryKamiInput}`)
            .then(response => {
                if (!response.ok) {
                    throw new Error('请求失败');
                }
                return response.json();
            })
            .then(data => {
                if (data.code == 200) {
                    // 显示查询结果
                    Swal.fire({
                        title: '查询结果',
                        html: `
                            <p>卡密: ${queryKamiInput}</p>
                            <p>类型: ${data.type}</p>
                            <p>状态: ${data.item}</p>
                        `,
                        icon: 'info'
                    });
                } else {
                    // 查询失败
                    Swal.fire({
                        title: '查询失败',
                        text: data.message || '未找到卡密信息！',
                        icon: 'error'
                    });
                }
            })
            .catch(error => {
                // 显示错误信息
                Swal.fire({
                    title: '查询失败',
                    text: error.message,
                    icon: 'error'
                });
            });
    });

    // 卡密授权表单提交事件
    document.getElementById('authForm').addEventListener('submit', function(event) {
        event.preventDefault(); // 阻止表单默认提交行为

        const lxqq = document.getElementById('lxqq').value; // 联系人QQ
        const sqqq = document.getElementById('sqqq').value; // 机器人QQ
        const kami = document.getElementById('kami1').value; // 卡密

        // 检查输入是否为空
        if (!lxqq || !sqqq || !kami) {
            Swal.fire({
                title: '授权失败',
                text: '所有字段均为必填项，请填写完整信息！',
                icon: 'error'
            });
            return;
        }

        // 构造查询字符串
        const queryParams = new URLSearchParams({
            lxqq: lxqq,
            qq: sqqq,
            kami: kami
        }).toString();

        // 发起请求进行卡密授权
        fetch(`api/auth.php?${queryParams}`)
            .then(response => {
                if (!response.ok) {
                    throw new Error(`请求失败，状态码：${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                if (data.code == 200) {
                    // 授权成功
                    Swal.fire({
                        title: '授权成功',
                        text: data.message || '您已成功授权！',
                        icon: 'success'
                    });
                } else {
                    // 授权失败
                    Swal.fire({
                        title: '授权失败',
                        text: data.message || '授权失败，请检查卡密或联系管理员！',
                        icon: 'error'
                    });
                }
            })
            .catch(error => {
                // 显示错误信息
                Swal.fire({
                    title: '授权失败',
                    text: error.message,
                    icon: 'error'
                });
            });
    });
    </script>
</body>
</html>
